<template>
  <v-container fluid fill-height class="statistics-wrapper">
    <v-layout row wrap justify-center>
      <v-flex  md8 sm10 xs12 class="mt-3">
        <v-layout row>
          <v-flex md6 xs4>
            <v-btn icon @click="$router.go(-1)">
              <v-icon>arrow_back</v-icon>
            </v-btn>
          </v-flex>
          <v-flex md6 xs6 headline d-flex justify-center>
            <span>{{pageTitle}}</span>
          </v-flex>
        </v-layout>
        <v-divider></v-divider>
      </v-flex>
      <v-flex  md8 sm10 xs12>
        <v-layout column>
          <v-flex md8 xs12 class="px-2 mb-3">
            <v-card color="white">
              <v-card-title class="title card-title-bg">
                <v-icon>attach_file</v-icon>
                <span class="mx-2">需求信息 </span>
              </v-card-title>
              <v-divider></v-divider>
              <v-card-text class="title">
                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>需求名称</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-text-field hide-details :disabled="editable" single-line v-model="editItem.demand.demandName"></v-text-field>
                  </v-flex>
                </v-layout>

                <!-- <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>所属公众号</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-select  hide-details :disabled="editable" :items="area_items" v-model="editItem.demand.areaId"></v-select>
                  </v-flex>
                </v-layout> -->

                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>项目名称</span>
                  </v-flex>
                  <v-flex md6 xs8 d-flex nowrap>
                    <v-flex md4 xs4>
                    <v-select @change="changeArea"  hide-details :disabled="editable" :items="area_items" v-model="editItem.demand.areaId"></v-select>
                  </v-flex>
                  <v-flex md8 xs8>
                    <v-select  hide-details :disabled="editable" :items="state_projects" v-model="editItem.demand.projectName"></v-select>
                  </v-flex>
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>所属部门</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-select  hide-details :disabled="editable" :items="state_departments" v-model="editItem.ddRecord.department"></v-select>
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>需求负责人</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-text-field hide-details :disabled="editable" name="input-3" single-line v-model="editItem.demand.demandHead"></v-text-field>
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center v-if="showTime">
                  <v-flex md3 xs4>
                    <span>提交时间</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-menu ref="dateMenu1" :close-on-content-click="false" v-model="dateMenu1" :nudge-right="40" lazy transition="scale-transition"
                      offset-y full-width max-width="290px" min-width="290px">
                      <v-text-field slot="activator" v-model="editItem.ddRecord.createTime" label="请输入日期" hint="年年年年/月月/日日" persistent-hint prepend-icon="event"></v-text-field>
                      <v-date-picker locale="zh-cn" v-model="editItem.ddRecord.createTime" no-title @input="dateMenu1 = false"></v-date-picker>
                    </v-menu>
                    <!-- <v-text-field  :disabled="editable" @input="dateChanged" mask="####-##-##" v-model="editItem.demand.createTime" label="请按格式输入日期" hint="年年年年-月月-日日" persistent-hint prepend-icon="event"></v-text-field> -->
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center v-if="showTime">
                  <v-flex md3 xs4>
                    <span>完成时间</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-menu ref="dateMenu2" :close-on-content-click="false" v-model="dateMenu2" :nudge-right="40" lazy transition="scale-transition"
                      offset-y full-width max-width="290px" min-width="290px">
                      <v-text-field slot="activator" v-model="editItem.ddRecord.deadTime" label="请输入日期" hint="年年年年/月月/日日" persistent-hint prepend-icon="event"></v-text-field>
                      <v-date-picker locale="zh-cn" v-model="editItem.ddRecord.deadTime" no-title @input="dateMenu2 = false"></v-date-picker>
                    </v-menu>
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>需求详情</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-textarea hide-details name="input-3" outline v-model="editItem.demand.demandDetails"></v-textarea>
                  </v-flex>
                </v-layout>

                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>需求附件</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <form id="upload-form" enctype="multipart/form-data" method="post" class="drop-file text-xs-center cursor">
                      <input type="file" multiple name="demandFile" @change="selectFile(1)" class="file-input" />
                      <span d-flex align-center justify-center>
                        <v-icon size="30">cloud_upload</v-icon>
                        <span class="subheading">{{demandFileName}}</span>
                      </span>
                    </form>
                  </v-flex>
                </v-layout>

              </v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="(item, i) in editItem.versionList" :key="i" md8 xs12 class="px-2 my-2" v-if="$route.query.type !== 'add'">
            <v-card color="white">
              <v-card-title class="title card-title-bg">
                <v-icon>update</v-icon>
                <span class="mx-2">工作记录</span>
              </v-card-title>
              <v-divider></v-divider>
              <v-card-text class="title">
                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>版本号</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-text-field :disabled="editable" hide-details name="versionNumber" v-model="item.versionNumber" single-line></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout row align-baseline justify-center v-if="showTime">
                  <v-flex md3 xs4>
                    <span>提交时间</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-layout row nowrap align-center>
                  <v-flex md6 xs6>
                      <v-menu ref="dateMenu1" :close-on-content-click="false" v-model="dateMenus1[i]" :nudge-right="40" lazy transition="scale-transition"
                      offset-y full-width max-width="290px" min-width="290px">
                      <v-text-field :disabled="editable" slot="activator" v-model="item.createTime" label="请输入日期" hint="年年年年/月月/日日" persistent-hint prepend-icon="event"></v-text-field>
                      <v-date-picker :disabled="editable" locale="zh-cn" v-model="item.createTime" no-title @input="dateMenus1[i] = false"></v-date-picker>
                    </v-menu>
                  </v-flex>
                  <v-flex md6 xs6>
                    <v-text-field :disabled="editable" hint="时时:分分" mask="##:##"  label="请输入时间" name="exactTime" v-model="item.exactTime" single-line></v-text-field>
                  </v-flex>
                    </v-layout>
                  </v-flex>
                </v-layout>
                <v-layout row align-baseline justify-center class="my-2">
                  <v-flex md3 xs4>
                    <span>版本负责人</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-text-field :disabled="editable" hide-details name="director" v-model="item.director" single-line></v-text-field>
                  </v-flex>
                </v-layout>
                <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>版本记录</span>
                  </v-flex>
                  <v-flex md6 xs8>
                    <v-textarea hide-details name="record" v-model="item.content" outline></v-textarea>
                  </v-flex>
                </v-layout>

                <!-- <v-layout row align-baseline justify-center>
                  <v-flex md3 xs4>
                    <span>测试记录</span>
                  </v-flex>
                  <v-flex md4>
                    <v-btn flat @click="openDialog(2)" class="title teal--text">添加测试记录</v-btn>
                  </v-flex>
                </v-layout> -->
              </v-card-text>
            </v-card>
          </v-flex>
        </v-layout>
      </v-flex>

      <v-flex md12 xs12 v-if="showButton == 1" class="text-md-center">
        <v-btn color="blue" class="title" dark @click="confirmAdd" type="button">确认</v-btn>
        <v-btn color="red" class="title" dark @click="$router.go(-1)" type="button">取消</v-btn>
      </v-flex>
      <v-flex md12 xs12 v-else-if="showButton == 2" class="text-md-center">
        <v-btn color="red" class="title" dark @click="$router.go(-1)">取消</v-btn>
        <v-btn color="blue" class="title" dark @click="openDialog(1)">部门移交</v-btn>
        <v-btn color="teal" class="title" dark @click="uploadVersion">版本提交</v-btn>
      </v-flex>
      <v-flex md12 xs12 v-else class="text-md-center">
        <v-btn color="red" class="title" dark @click="$router.go(-1)">返回</v-btn>
      </v-flex>

    </v-layout>
    <v-dialog scrollable v-model="dialog" class="demand-details-dialog" max-width="600px">
      <v-card>
        <v-card-title class="elevation-1">

          <span class="headline">
            <v-icon size="32">report</v-icon>
            {{ dialogTitle }}
          </span>
        </v-card-title>
        <v-card-text>
          <v-layout wrap column class="px-4" v-show="dialogType == 1">
            <v-flex xs12 md8 class="text-xs-right">
              <v-btn color="teal" dark icon :disabled="toDpItems.length === 3" @click="addToDpItem">
                <v-icon>add</v-icon>
              </v-btn>
              <v-btn color="red" dark icon :disabled="toDpItems.length === 1" @click="removeToDpItem">
                <v-icon>remove</v-icon>
              </v-btn>
            </v-flex>

            <div v-for="(item,i) in toDpItems" :key="i" class="to-dp-wrapper py-3 px-3 my-2">
              <v-flex xs12>
                <v-select label="移交部门" prepend-icon="assignment" :items="state_departments" v-model="item.department"></v-select>
              </v-flex>
              <v-flex xs12>
                <v-menu :close-on-content-click="false" v-model="dateMenus[i]" :nudge-right="40" lazy transition="scale-transition"
                      offset-y full-width max-width="290px" min-width="290px">
                  <v-text-field  slot="activator" v-model="item.deadTime" label="请输入日期" hint="年年年年/月月/日日" persistent-hint prepend-icon="event"></v-text-field>
                  <v-date-picker locale="zh-cn" v-model="item.deadTime" no-title @input="dateMenus[i] = false"></v-date-picker>
                </v-menu>
              </v-flex>
            </div>

          </v-layout>
          <v-layout wrap column class="px-4" v-show="dialogType == 2">
            <v-flex xs12 md8 class="text-xs-right">
              <v-btn color="teal" dark icon :disabled="testRecItems.length === 3" @click="addTestRecItems">
                <v-icon>add</v-icon>
              </v-btn>
              <v-btn color="red" dark icon :disabled="testRecItems.length === 1" @click="removeTestRecItems">
                <v-icon>remove</v-icon>
              </v-btn>
            </v-flex>
            <div v-for="(item,i) in testRecItems" :key="i" class="to-dp-wrapper py-3 px-3 my-2">
              <v-flex sm12>
                <v-text-field prepend-icon="av_timer" label="提交时间" v-model="item.uploadTime"></v-text-field>
              </v-flex>
              <v-flex sm12>
                <v-text-field prepend-icon="waves" label="测试环境" v-model="item.testEnv"></v-text-field>
              </v-flex>
              <v-flex sm12>
                <v-textarea prepend-icon="comment" label="测试结果" outline v-model="item.result"></v-textarea>
              </v-flex>
              <v-divider></v-divider>
            </div>
          </v-layout>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="red darken-1" flat @click.native="dialog = false">取消</v-btn>
          <v-btn color="blue darken-1" flat @click.native="confirmDialog">确认</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
import * as demand from "../../api/demand";
// import PROJECT from "../../util/projects";
import { getTime, getTimeFromString, parseDate, getDateFromString, parseDateTime } from "../../util";
import { mapState } from 'vuex'

export default {
  data: () => ({
    dialog: false,
    dialogType: 1,
    dialogTitle: "部门移交",
    modal: false,
    modalText: "",
    demandid: "",
    projTypesItems: {
      '0': '无',
      '1': '客户端',
      '2': '服务端',
    },
    toDpItems: [
      {
        department: "",
        deadTime: "",
        timeMenu: null
      }
    ],
    testRecItems: [
      {
        uploadTime: "",
        testEnv: "",
        result: ""
      }
    ],
    dateMenus: [],
    dateMenus1: [],
    dpTitle: "",
    dayData: {},
    showTime: false,
    showButton: false,
    pageTitle: "",
    editItem: {
      demand: {},
      ddRecord:{},
      versionList: []
    },
    demandFileName: "请选择文件",
    demandFile: null,
    testFile: "请添加测试记录",
    createTime: "",
    dateMenu1: null,
    dDate1: "",
    dDate2: "",
    dateMenu2: null,

    timeMenu: null,
    type: 'add',
    editable: false,
    department: 0,
    state_projects: [{
      text: '请选择项目公众号',
      value: -1
    }],
    area_items: []
  }),
  computed: {
    ...mapState(['state_departments'])
  },
  mounted() {
    this.area_items = window.AREAS
    let type = this.$route.query.type;
    this.type = type;
    this.showTime = true;
    this.showButton = (type == "edit") ? 2 : 1;
    this.department = this.$route.query.department
    if (type == "add") {
      this.pageTitle = "新增需求";
    }
    if (type == "details") {
      this.pageTitle = "需求详情";
      this.demandid = this.$route.query.demandid;

      this.getDemandDetails();
      this.editable = true;
      this.showButton = 3
    }
    if (type == "edit") {
      this.pageTitle = "编辑需求";
      this.demandid = this.$route.query.demandid;
      this.getDemandDetails();
    }
    if(type == 'modify') {
      this.pageTitle = "编辑需求";
      this.demandid = this.$route.query.demandid;
      this.getDemandDetails();
    }

    let dp = this.$route.query.dp;
    // this.getProjectList();
    // this.getDepartmentList();

  },
  watch: {
    // 监测路由参数变化
    $route(to, from) {
      console.log(to.params.gametype);
    }
  },
  filters: {},
  methods: {
    getTime,
    getProjectList() {
      demand.getProjectList.r().then(({ data }) => {
        // console.error(JSON.stringify(data.data.dataList));
        let d = data.data;
        if (data.result == 0) {
          let projects = [];
          _.forEach(d.dataList, (item, i)=>{
            // console.log(item)
            projects.push({
              text: item.projectName + '-' + (item.type == 1 ? '客户端': '服务端'),
              value: item.id
            })
          })
          this.state_projects = projects;
        }
      });
    },
    // getDepartmentList() {
    //   demand.getDepartmentList.r().then(({ data }) => {
    //     let d = data.data;
    //     if (data.result == 0) {
    //       let departments = [];
    //       _.forEach(d.dataList, (item, i)=>{
    //         departments.push({
    //           text: item.departmentName,
    //           value: item.id
    //         })
    //       })
    //       this.state_departments = departments;
    //     }

    //   });
    // },
    getDemandDetails() {
      let opt = {
        id: this.demandid,
        department: this.department
      };
      demand.getDemandDetails.r(opt).then(({ data }) => {
        let d = data.data;
        console.error(d)
        let demand = Object.assign({}, d.demand)
        let versionList = d.versionList.slice()
        if (data.result == 0) {
          demand.createTime = parseDate(demand.createTime);
          demand.deadTime = parseDate(demand.deadTime);
          versionList.forEach(item => {
            let et = parseDateTime(item.createTime).split(' ')[1]
            item.createTime = parseDate(item.createTime);
            item.exactTime = et
          });
          if (this.type == 'edit') {
          versionList.push({
            versionNumber: '',
            createTime: '',
            director: '',
            content: '',
          })
          }
          let ddRecord = d.ddRecord
          let project = d.project
          ddRecord.createTime = parseDate(ddRecord.createTime);
          ddRecord.deadTime = parseDate(ddRecord.deadTime);

          demand.oldDepartment = ddRecord.department

          this.editItem = {demand, versionList, ddRecord, project};
        }
      });
    },
    modifyDemand() {
      let opt = Object.assign({}, this.editItem.demand)
      opt.createTime2 = this.editItem.ddRecord.createTime
      opt.deadTime2 = this.editItem.ddRecord.deadTime
      opt.department = this.editItem.ddRecord.department
      if(!opt.createTime || !opt.deadTime){
        return $Vue.$emit("toggleSnackbar", {
          text: '请选择日期.'
        });
      }
      opt.demandId = opt.id
      delete opt.id
      opt.createTime2 = new Date((opt.createTime2).replace(/-/g, '/') + ' 00:00:00').getTime()
      opt.deadTime2 = new Date((opt.deadTime2).replace(/-/g, '/')+ ' 23:59:59').getTime()
      let form = new FormData();
      delete opt.createTime
      delete opt.deadTime
      console.log(opt)
      demand.modifyDemand.r(opt).then(({ data }) => {
        $Vue.$emit("toggleSnackbar", {
          text: data.message
        });
        if (data.result == 0) {
          this.$router.go(-1);
        }
      });
    },
    addDemand() {
      let opt = Object.assign({}, this.editItem.demand)
      opt.createTime = this.editItem.ddRecord.createTime
      opt.deadTime = this.editItem.ddRecord.deadTime
      opt.department = this.editItem.ddRecord.department
      if(!opt.createTime || !opt.deadTime){
        return $Vue.$emit("toggleSnackbar", {
          text: '请选择日期.'
        });
      }
      opt.createTime = new Date((opt.createTime).replace(/-/g, '/') + ' 00:00:00').getTime()
      opt.deadTime = new Date((opt.deadTime).replace(/-/g, '/')+ ' 23:59:59').getTime()
      let form = new FormData();
      form.append("file", this.demandFile);
      form.append("details", this.editItem);
      demand.addDemand.r(opt).then(({ data }) => {
        console.log(data);
        $Vue.$emit("toggleSnackbar", {
          text: data.message
        });
        if (data.result == 0) {
          this.$router.go(-1);
        }
      });
    },
    // 部门移交
    handoverDemand() {
      // console.error(this.toDpItems.slice(0))
      let toDpItems = []
      _.forEach(this.toDpItems, (item)=>{
        toDpItems.push(_.assign({},item))
      })
      let opt = {
        ..._.last(this.editItem.versionList),
        handoverList: toDpItems,
        demandId: +this.$route.query.demandid
      };
      opt.department = this.$route.query.department;
      let cancel = false;
      opt.handoverList.forEach(item=>{
        if(!item.deadTime) {
          cancel = true
        }
        item.deadTime = new Date((item.deadTime).replace(/-/g, '/') + ' 23:59:59').getTime()
      })
      if(cancel) {
        return $Vue.$emit("toggleSnackbar", {
          text: '请选择完整日期.'
        });
      }
      console.log(opt)

      let time = opt.exactTime.match(/(\d{2})(\d{2})/)

      if(opt.createTime.length < 10 || opt.exactTime.length < 4) {
        return $Vue.$emit("toggleSnackbar", {
          text: '请选择完整日期时间.'
        });
      }
      opt.createTime = opt.createTime + ` ${time[1]}:${time[2]}:00`
      opt.createTime = new Date(opt.createTime.replace(/\-/g, '/')).getTime()
      demand.handoverDemand.r(opt).then(({ data }) => {
        $Vue.$emit("toggleSnackbar", {
          text: data.message
        });
        if (data.result == 0) {
          this.$router.go(-1);
        }
      });
    },
    // 版本
    pushVerison() {
      // console.log(this.editItem)
      let opt = {
        ..._.last(this.editItem.versionList),
        demandId: +this.$route.query.demandid,
        department : this.department,
        projectName: this.editItem.demand.projectName
      }
      let time = opt.exactTime.match(/(\d{2})(\d{2})/)

      if(opt.createTime.length < 10 || opt.exactTime.length < 4) {
        return $Vue.$emit("toggleSnackbar", {
          text: '请选择完整日期时间.'
        });
      }
      opt.createTime = opt.createTime + ` ${time[1]}:${time[2]}:00`
      opt.createTime = new Date(opt.createTime.replace(/\-/g, '/')).getTime()

      // console.log(opt)
      demand.pushVerison.r(opt).then(({ data }) => {
        $Vue.$emit("toggleSnackbar", {
          text: data.message
        });
        if (data.result == 0) {
          this.$router.go(-1);
        }
      });
    },
    getAreaProjects() {
      let opt = {
        areaId: this.editItem.demand.areaId
      }
      demand.getAreaProjects.r(opt).then(({ data }) => {
        console.log(data)
        if (data.result == 0) {
          let d = data.data.dataList
          let items = []
          d.forEach(item=>{
            items.push({
              text: item.projectName + '-' + (item.type == 1 ? '客户端': '服务端'),
              value: item.id
            })
          })
          this.state_projects = items
        }
      });
    },
    dateChanged(ev, item) {
      console.log(ev, item);
    },
    confirmAdd() {
      // this.addVersionRecord();
      console.log(JSON.stringify(this.editItem));
      if(this.type === 'modify') {
        this.modifyDemand()
      }else{
        this.addDemand();
      }

    },
    selectFile(type) {
      var oFile = event.target.files[0];
      var fileReader = new FileReader();
      this.demandFile = oFile;
      if (type === 1) {
        this.demandFileName = oFile.name;
      } else {
        this.testFile = oFile.name;
      }

      // fileReader.onload = function() {
      //   var base64URL = this.result;
      // };

      fileReader.readAsDataURL(oFile);
    },
    uploadVersion(){
      this.pushVerison();
    },
    openDialog(type) {
      this.dialogType = type;
      this.dialogTitle = type == 1 ? "部门移交" : "版本移交";
      this.dialog = true;
    },
    confirmDialog() {
      this.handoverDemand();
      // this.addDemand()
    },
    addToDpItem() {
      this.toDpItems.push({
        department: "",
        deadTime: "",
        timeMenu: null
      });
    },
    removeToDpItem() {
      this.toDpItems.pop();
    },
    addTestRecItems() {
      this.testRecItems.push({
        uploadTime: "",
        testEnv: "",
        result: ""
      });
    },
    removeTestRecItems() {
      this.testRecItems.pop();
    },
    changeArea(value) {
      console.log(value)
      this.getAreaProjects()
    }
  }
};
</script>

<style lang="less" scoped>
.drop-file {
  width: 100%;
  height: 40px;
  border: 2px dashed #afafaf;
  border-radius: 8px;
  position: relative;
  transition: 0.2s all ease-in-out;
  i {
    transition: inherit;
  }
  &:hover {
    border-color: #009688;
    i {
      color: #009688;
    }
  }
}
.file-input {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  &:hover {
    cursor: pointer;
  }
}
.to-dp-wrapper {
  border: 1px dashed #afafaf;
}
</style>


